package com.example.logindemo01;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class HomePage extends AppCompatActivity {
    private String homeUrl = "https://www.wanandroid.com/article/list/0/json";
    private String logoutUrl = "https://www.wanandroid.com/user/logout/json";
    private List<Article> articleList = new ArrayList<>();
    ListView listView;
    MyAdapter myAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_page);
        myAdapter = new MyAdapter();
        listView = findViewById(R.id.listview);
        listView.setAdapter(myAdapter);

        new Thread(){
            @Override
            public void run() {
                String jsonString = getJsonString(homeUrl);
                articleList = parseJson(jsonString);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        myAdapter.notifyDataSetChanged();
                    }
                });
            }
        }.start();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(HomePage.this,ReadActivity.class);
                intent.putExtra("link",articleList.get(position).getTitle());
                startActivity(intent);
            }
        });
    }

    private List<Article> parseJson(String jsonString) {
        List<Article> articles = new ArrayList<>();
        try {
            JSONObject object = new JSONObject(jsonString);
            int errorCode = object.optInt("errorCode");
            if(errorCode!=0)
                return null;
            JSONObject object1 = object.optJSONObject("data");
            JSONArray datas = object1.optJSONArray("datas");
            for(int i=0;i<datas.length();i++){
                JSONObject object2 = datas.optJSONObject(i);
                String title = object2.optString("title");
                String author = object2.optString("author");
                String link = object2.optString("link");
                Article article = new Article(title,author,link);
                articles.add(article);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return articles;
    }

    public void onClick1(View view) {
        new Thread(){
            @Override
            public void run() {
                try{
                    String logout = logout();
                    JSONObject object = new JSONObject(logout);
                    int errorCode = object.optInt("errorCode");
                    String errorMsg = object.optString("errorMsg");
                    if (errorCode==0){
                        System.out.println("退出成功");
                        Intent intent=new Intent();
                        intent.setClass(HomePage.this, MainActivity.class);
                        startActivity(intent);
                    }else {
                        System.out.println("退出失败");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private String logout(){
        try {
            URL url = new URL(logoutUrl);
            HttpURLConnection cn = (HttpURLConnection) url.openConnection();
            if (cn.getResponseCode()==200){
                InputStream inputStream = cn.getInputStream();
                String s = stream2String(inputStream);
                return s;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String getJsonString(String path){
        try {
            URL url=new URL(path);
            HttpURLConnection cn= (HttpURLConnection) url.openConnection();
            InputStream inputStream = cn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer buffer = new StringBuffer();
            String line = null;
            while ((line=br.readLine())!=null){
                buffer.append(line);
            }
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
//        try{
//            URL url=new URL(path);
//            HttpURLConnection cn= (HttpURLConnection) url.openConnection();
//            InputStream inputStream = cn.getInputStream();
//            byte[] bytes = new byte[1024];
//            int len = 0;
//            while ((len=inputStream.read(bytes))!=-1){
//                String s = new String(bytes);
//                return s;
//            }
//        } catch (Exception e){
//            e.printStackTrace();
//        }
//        return null;
    }

    private String stream2String(InputStream is) {
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuffer sb = new StringBuffer();
        String line;
        try {
            while ((line=br.readLine()) != null) {
                sb.append(line);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return sb.toString();
    }

    class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return articleList.size();
        }
        @Override
        public Object getItem(int position) {
            return position;
        }
        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder, holder1;
            if (convertView == null) {
                convertView = LayoutInflater.from(HomePage.this)
                        .inflate(R.layout.list_item, parent, false);
                holder = new ViewHolder();
                holder.tv_title = convertView.findViewById(R.id.tv_title);
                holder.tv_author = convertView.findViewById(R.id.tv_author);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.tv_title.setText("标题： "+articleList.get(position).getTitle());
            holder.tv_author.setText("作者： "+articleList.get(position).getAuthor());
            return convertView;
        }
    }

    static class ViewHolder {
        TextView tv_title;
        TextView tv_author;
    }
}